<template>
  <div class="make-addKnowledgeBase">
    <div class="header">选择数据源</div>

    <div class="tab-btns">
      <div
        class="tab-btn"
        @click="handleChange('import')"
        :class="{ active: activeTab === 'import' }"
      >
        <span class="icon"><img src="@/assets/img/fromdoc.png" alt="" /></span>
        <span class="text">导入已有文本</span>
      </div>
      <div
        class="tab-btn"
        @click="handleChange('internet')"
        :class="{ active: activeTab === 'internet' }"
      >
        <span class="icon"><img src="@/assets/img/fromweb.png" alt="" /></span>
        <span class="text">从互联网获取</span>
      </div>
    </div>

    <!-- 导入已有文本 -->
    <div class="import-content" v-if="activeTab === 'import'">
      <div class="title">上传文本文件</div>
      <el-upload
        ref="uploadRef"
        class="avatar-uploader"
        action=""
        :on-change="handleFileChange"
        :on-remove="handleRemove"
        :limit="1"
        accept=".txt, .md, .csv"
        :auto-upload="false"
        :on-exceed="handleExceed"
        drag
      >
        <div class="upload-box">
          <div class="box-one">
            <div class="img-box">
              <img src="@/assets/img/zhishi/upload.png" />
            </div>
            <div class="one-txt">导入本地文件，点击上传或拖拽文件到这里</div>
            <div class="one-subtxt">
              支持 txt、markdown、csv，每个文件不超过15MB
            </div>
          </div>
        </div>
      </el-upload>
      <!-- <div class="uploadFile">
        <div class="file-name">{{ uploadedFileName }}</div>
      </div> -->
      <el-button
        v-show="activeTab === 'import'"
        type="primary"
        color="#457aff"
        style="width: 120px"
        :disabled="!canClickNext"
        @click="importFileSave()"
        >保存</el-button
      >
    </div>

    <!-- 从互联网获取 -->
    <div class="internet-content" v-if="activeTab === 'internet'">
      <div class="url-input-section">
        <div class="input-wrapper">
          <el-input
            v-model="websiteUrl"
            placeholder="https://docs.dify.ai"
            class="url-input"
          />
          <el-button
            type="primary"
            class="run-btn"
            @click="handleRun()"
            :loading="isRunning"
            :disabled="isRunning"
            >运行</el-button
          >
        </div>
      </div>

      <div class="settings-section">
        <el-collapse v-model="activeSettingsName" class="settings-collapse">
          <el-collapse-item name="settings">
            <template #title>
              <div class="title-txt">
                <i class="iconfont icon-peizhiguanli"></i> 选项
              </div>
            </template>
            <div class="settings-content">
              <div class="setting-item">
                <el-checkbox v-model="crawl_sub_pages" class="checkbox-item">
                  爬取子页面
                </el-checkbox>
              </div>

              <div class="setting-list">
                <div class="setting-item">
                  <div class="setting-row">
                    <div class="setting-label">限制数量</div>
                    <div class="setting-input">
                      <el-input v-model="limitNumber" class="depth-input" />
                    </div>
                  </div>
                </div>

                <div class="setting-item">
                  <div class="setting-row">
                    <div class="setting-label">最大深度</div>
                    <div class="setting-input">
                      <el-input
                        v-model="maxDepth"
                        placeholder="blog/, /about/"
                        class="specific-input"
                      />
                    </div>
                  </div>
                </div>

                <div class="setting-item">
                  <div class="setting-row">
                    <div class="setting-label">排除路径</div>
                    <div class="setting-input">
                      <el-input
                        v-model="excludePath"
                        placeholder="articles/"
                        class="include-input"
                      />
                    </div>
                  </div>
                </div>

                <div class="setting-item">
                  <div class="setting-row">
                    <div class="setting-label">仅包含路径</div>
                    <div class="setting-input">
                      <el-input
                        v-model="includePath"
                        placeholder="articles/"
                        class="include-input"
                      />
                    </div>
                  </div>
                </div>
              </div>

              <div class="setting-item">
                <div class="main-content-wrapper">
                  <el-checkbox
                    v-model="only_main_content"
                    class="checkbox-item"
                  >
                    仅提取主要内容
                    <span class="checkbox-desc">（无标题、导航、页脚等）</span>
                  </el-checkbox>

                  <!-- 骨架屏 -->
                  <!-- <div v-if="showSkeleton" class="skeleton-content">
                    <div class="skeleton-lines">
                      <div class="skeleton-line"></div>
                      <div class="skeleton-line"></div>
                      <div class="skeleton-line short"></div>
                    </div>
                  </div> -->
                  <el-skeleton :rows="5" animated v-if="showSkeleton" />
                </div>
              </div>

              <div
                class="setting-item-row"
                v-if="jobData && jobData.length > 0"
              >
                <span class="item-checkbox">
                  <el-checkbox
                    v-model="resetAll"
                    v-show="resetAll"
                    @change="handleResetAll"
                  >
                    重置全部
                  </el-checkbox>
                  <el-checkbox
                    v-model="resetAll"
                    v-show="!resetAll"
                    @change="handleResetAll"
                  >
                    全选
                  </el-checkbox>
                </span>
                <span class="item-text"
                  >总共在{{ time_consuming }}秒内抓取了{{
                    total_pages
                  }}个页面</span
                >
              </div>

              <div class="checkbox-list" v-if="jobData && jobData.length > 0">
                <div
                  class="checkbox-item"
                  v-for="(item, index) in jobData"
                  v-show="index == 0"
                  :key="item.id"
                >
                  <el-checkbox
                    v-model="item.checked"
                    @change="handleCheckboxChange"
                  />
                  <div class="job-item-info">
                    <span class="checkbox-text">{{ item.title }}</span>
                    <span class="checkbox-url">{{ item.source_url }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <el-button
        v-show="activeTab === 'internet'"
        type="primary"
        color="#457aff"
        style="width: 120px"
        :disabled="!canClickNext"
        @click="saveKnowledgeBase()"
        >保存</el-button
      >
    </div>

    <!-- 完成 -->
    <!-- <el-button
      v-show="activeTab === 'internet'"
      type="primary"
      color="#457aff"
      style="width: 120px; margin-top: 20px"
      @click="completeFn()"
      >完成</el-button
    > -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      courseId: "",
      knowledgeId: "",
      job_id: "",
      job_status: "",
      job_timer: null,
      jobData: [],
      time_consuming: "",
      current_page: 0,
      total_pages: 0,
      activeTab: "import",
      // 从互联网获取相关数据
      websiteUrl: "",
      activeSettingsName: ["settings"],
      crawl_sub_pages: true,
      limitNumber: 10,
      maxDepth: "",
      excludePath: "",
      includePath: "",
      only_main_content: true,
      // 新增状态控制
      isFileUploaded: false,
      isRunning: false,
      showSkeleton: false,
      resetAll: true,
      uploadedFile: null,
      uploadedFileName: "",
      fileContent: "", // 解析文本内容
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.knowledgeId = this.$route.query.id;
  },
  beforeDestroy() {
    // 组件销毁前清理定时器
    if (this.job_timer) {
      clearTimeout(this.job_timer);
      this.job_timer = null;
    }
  },
  computed: {
    // 计算下一步按钮是否可点击
    canClickNext() {
      if (this.activeTab === "import") {
        return this.isFileUploaded;
      } else if (this.activeTab === "internet") {
        return this.job_status === "completed";
      }
      return false;
    },
  },
  methods: {
    // 切换tab
    handleChange(val) {
      this.activeTab = val;
    },

    // 超出限制
    handleExceed() {
      this.$message.warning("只能上传一个文件");
    },

    // 处理文件变化
    handleFileChange(file) {
      // 检查文件格式
      const allowedTypes = [".txt", ".md", ".csv"];
      const fileName = file.name.toLowerCase();
      const isValidType = allowedTypes.some((type) => fileName.endsWith(type));

      if (!isValidType) {
        this.$message.error("只支持上传txt、markdown、csv文件格式");
        // 清除已上传的文件
        this.$refs.uploadRef.clearFiles();
        this.uploadedFile = null;
        this.uploadedFileName = "";
        this.isFileUploaded = false;
        return;
      }
      const fileSize = file.size / 1024 / 1024;
      if (fileSize > 15) {
        this.$message.error("文件大小不能超过15MB，请重新上传");
        // 清除已上传的文件
        this.$refs.uploadRef.clearFiles();
        this.uploadedFile = null;
        this.uploadedFileName = "";
        this.isFileUploaded = false;
        return;
      }

      this.uploadedFile = file.raw;
      this.uploadedFileName = file.name;
      this.isFileUploaded = true;
    },
    handleRemove(file) {
      this.uploadedFile = null;
      this.uploadedFileName = "";
      this.isFileUploaded = false;
    },

    // 文本解析
    importFileSave() {
      const formData = new FormData();
      formData.append("file", this.uploadedFile);
      this.$axios
        .post(`/tes/course/auto/make/analyzeDocument`, formData)
        .then((res) => {
          this.fileContent = res.data;
          this.saveKnowledgeBase();
        });
    },

    // 重置全部
    handleResetAll() {
      this.jobData.forEach((item) => {
        item.checked = this.resetAll;
      });
    },

    // 选中状态变化
    handleCheckboxChange() {
      this.resetAll = this.jobData.every((item) => item.checked);
    },

    // 运行爬取
    handleRun() {
      if (!this.websiteUrl) {
        this.$message.warning("请输入网站URL");
        return;
      }
      if (this.job_status && this.job_status === "completed") {
        this.jobData = [];
        this.job_status = "";
      }
      const queryObj = {
        url: this.websiteUrl,
        options: {
          crawl_sub_pages: this.crawl_sub_pages,
          only_main_content: this.only_main_content,
          includes: this.includePath,
          excludes: this.excludePath,
          limit: this.limitNumber,
          use_sitemap: true,
        },
        provider: "firecrawl",
      };

      this.$axios
        .post(`/tes/dify-api/website/crawl`, queryObj)
        .then((res) => {
          this.job_id = res.data.job_id;
          // 清除之前可能存在的定时器
          if (this.job_timer) {
            clearTimeout(this.job_timer);
            this.job_timer = null;
          }
          // 立即执行一次状态检查
          this.getJobStatus();
        })
        .catch((err) => {
          this.isRunning = false;
          this.showSkeleton = false;
        });

      // 设置加载状态
      this.isRunning = true;
      this.showSkeleton = true;
    },

    // 获取爬虫状态
    getJobStatus() {
      this.$axios
        .get(`/tes/dify-api/website/crawl/status/${this.job_id}`)
        .then((res) => {
          this.job_status = res.data.status;
          if (this.job_status === "completed") {
            this.jobData = res.data.data;
            // 为每个数据项添加 checked 属性并设为 true
            this.jobData = this.jobData.map((item, index) => ({
              ...item,
              id: index + 1,
              checked: true,
            }));
            this.time_consuming = res.data.time_consuming;
            this.total_pages = res.data.total;
            // 任务完成，清理状态
            if (this.job_timer) {
              clearTimeout(this.job_timer);
              this.job_timer = null;
            }
            this.isRunning = false;
            this.showSkeleton = false;
          } else {
            // 任务未完成，设置下一次轮询
            this.job_timer = setTimeout(() => {
              this.getJobStatus();
            }, 3000);
          }
        })
        .catch((error) => {
          this.isRunning = false;
          this.showSkeleton = false;
        });
    },

    // 保存知识库
    saveKnowledgeBase() {
      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let queryObj = {};
      if (this.activeTab === "import") {
        queryObj = {
          id: this.knowledgeId,
          courseId: this.courseId,
          content: this.fileContent,
          fileName: this.uploadedFileName,
          fileSize: (this.uploadedFile.size / 1024).toFixed(2) + "KB",
        };
      } else {
        queryObj = {
          id: this.knowledgeId,
          courseId: this.courseId,
          content: this.jobData[0].markdown,
        };
      }
      this.$axios
        .post(`/tes/course/auto/make/addCourseBookFileByData`, queryObj)
        .then((res) => {
          this.$message.success("保存成功");
          this.$router.push("/aiTeaching/courseBuild/makeKnowledgeBase");
        })
        .finally(() => {
          loading.close();
        });
    },

    // 完成
    completeFn() {
      this.$router.push("/aiTeaching/courseBuild/makeKnowledgeDetail");
    },
  },
};
</script>

<style lang="scss" scoped>
.make-addKnowledgeBase {
  background-color: #fff;
  padding: 40px 60px;
  box-sizing: border-box;
  .header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-weight: 700;
    font-size: 18px;
  }
  .tab-btns {
    margin-top: 22px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 20px;
    .tab-btn {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 10px;
      padding: 20px 15px;
      background-color: #fff;
      border-radius: 10px;
      border: 1px solid #e5e5e5;
      font-size: 16px;
      cursor: pointer;
      .icon {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 32px;
        height: 32px;
        background: #f5faff;
        border-radius: 8px;
        border: 1px solid #d1e9ff;
        box-sizing: border-box;
        img {
          width: 15px;
          height: 15px;
        }
      }
      &.active {
        background-color: #f5f8ff;
        border: 1px solid #127aff;
      }
    }
  }

  .import-content {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    gap: 10px;
    margin-top: 35px;
    padding-bottom: 35px;
    border-bottom: 1px solid #e5e5e5;
    .avatar-uploader {
      width: 100%;
      :deep(.el-upload-dragger) {
        border: none;
        padding: 0;
      }
      :deep(.el-upload) {
        width: 100%;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        border-radius: 10px;
        border: 1px dashed #bebebe;
        .upload-box {
          background: #fff;
          width: 100%;
          border-radius: 10px;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 20px 0 20px;
          > div {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          }
          .box-one {
            width: 60%;
            gap: 10px;
            .img-box {
              width: 31px;
              height: 23px;
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            .one-txt {
              font-size: 16px;
              color: #6b6a76;
            }
            .one-subtxt {
              font-size: 14px;
              color: #a2a0b3;
            }
          }
        }
      }
      margin-bottom: 10px;
    }
  }

  .internet-content {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    gap: 20px;
    margin-top: 35px;
    padding-bottom: 35px;
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #e5e5e5;

    .url-input-section {
      width: 100%;

      .input-wrapper {
        display: flex;
        gap: 10px;
        align-items: center;

        .url-input {
          flex: 1;
          :deep(.el-input__wrapper) {
            background-color: #f2f4f7;
            border: none;
            padding: 10px 15px;
            font-size: 14px;
          }
        }

        .run-btn {
          padding: 10px 20px;
          border-radius: 8px;
          font-size: 14px;
          background-color: #457aff;
          border-color: #457aff;
        }
      }
    }

    .settings-section {
      width: 100%;

      .settings-collapse {
        width: 100%;
        border: none;

        :deep(.el-collapse-item__header) {
          background-color: transparent;
          border: none;
          font-size: 14px;
          color: #666;
          padding: 0;
          height: auto;
          line-height: 1.5;
        }

        :deep(.el-collapse-item__content) {
          padding: 15px 0 0 0;
        }

        .settings-content {
          display: flex;
          flex-direction: column;
          gap: 10px;
          .setting-item-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .item-text {
              font-size: 14px;
              color: #999;
            }
          }
          .checkbox-list {
            display: flex;
            flex-direction: column;
            gap: 5px;
            .checkbox-item {
              display: flex;
              align-items: center;
              gap: 10px;
              .job-item-info {
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                justify-content: center;
                .checkbox-text {
                  max-width: 650px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  font-size: 14px;
                  color: #333;
                }
                .checkbox-url {
                  max-width: 650px;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                  font-size: 12px;
                  color: #999;
                }
              }
            }
          }
          .setting-list {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;

            .setting-item {
              width: calc(50% - 10px);
              display: flex;
              flex-direction: column;

              .checkbox-item {
                display: flex;
                align-items: center;
                font-size: 14px;
                color: #333;

                .checkbox-desc {
                  color: #999;
                  font-size: 12px;
                  margin-left: 5px;
                }

                :deep(.el-checkbox__label) {
                  font-size: 14px;
                  color: #333;
                }
              }

              .setting-row {
                width: 100%;
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                gap: 10px;

                .setting-label {
                  font-size: 14px;
                  color: #333;
                }

                .setting-input {
                  width: 100%;
                  .depth-input,
                  .specific-input,
                  .include-input {
                    :deep(.el-input__wrapper) {
                      background-color: #f2f4f7;
                      border: none;
                      font-size: 14px;
                    }
                  }
                }
              }
            }
          }

          // 新增的主要内容包装器和骨架屏样式
          .main-content-wrapper {
            position: relative;

            // .skeleton-content {
            //   margin-top: 15px;
            //   padding: 15px;
            //   background-color: #f8f9fa;
            //   border-radius: 8px;
            //   border: 1px solid #e9ecef;

            //   .skeleton-lines {
            //     display: flex;
            //     flex-direction: column;
            //     gap: 8px;

            //     .skeleton-line {
            //       height: 12px;
            //       background: linear-gradient(
            //         90deg,
            //         #e2e8f0 25%,
            //         #f1f5f9 50%,
            //         #e2e8f0 75%
            //       );
            //       background-size: 200% 100%;
            //       border-radius: 6px;
            //       animation: shimmer 1.5s infinite;

            //       &.short {
            //         width: 60%;
            //       }
            //     }
            //   }
            // }
          }
        }
      }
    }
  }
}

// 骨架屏动画
// @keyframes shimmer {
//   0% {
//     background-position: -200% 0;
//   }
//   100% {
//     background-position: 200% 0;
//   }
// }

// 禁用按钮样式
:deep(.el-button:disabled) {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #c0c4cc !important;
  cursor: not-allowed !important;
}
</style>